#!/usr/bin/python
# -*- coding: utf-8 -*-
#/*
# *      Copyright (C) 2011 by Tolin
# *
# *  This Program is free software; you can redistribute it and/or modify
# *  it under the terms of the GNU General Public License as published by
# *  the Free Software Foundation; either version 2, or (at your option)
# *  any later version.
# *
# *  This Program is distributed in the hope that it will be useful,
# *  but WITHOUT ANY WARRANTY; without even the implied warranty of
# *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# *  GNU General Public License for more details.
# *
# *  You should have received a copy of the GNU General Public License
# *  along with this program; see the file COPYING.  If not, write to
# *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# *  http://www.gnu.org/copyleft/gpl.html
# */

import urllib2, re, httplib, xbmc, xbmcgui, xbmcplugin, cookielib, xbmcaddon, os, urllib, urllib2, socket


#socket.setdefaulttimeout(50)


icon = xbmc.translatePath(os.path.join(os.getcwd().replace(';', ''), 'icon.png'))
siteUrl = 'watch.is'
httpSiteUrl = 'http://' + siteUrl
__settings__ = xbmcaddon.Addon(id='plugin.video.watch.do')
sid_file = os.path.join(xbmc.translatePath('special://temp/'), 'plugin_video_watch_do.sid')

username = __settings__.getSetting('username')
password = __settings__.getSetting('password')

if ( username == "" or password == "" ):
	__settings__.openSettings()
	username = __settings__.getSetting('username')
	password = __settings__.getSetting('password')

if ( username == "" or password == "" ):
	dialog = xbmcgui.Dialog()
	dialog.ok('Error', 'Нет Login-a или Пароля !!!')
	

user_data = [('username', username), ('password', password), ('login', ' ')]
login_data = urllib.urlencode(user_data)

cookieJar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))	    

req = urllib2.Request('http://watch.is/login', login_data)
req.add_header('Host' , 'watch.is')
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1')
req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
req.add_header('Accept-Encoding' , 'gzip, deflate')
req.add_header('Accept-Language', 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3')
req.add_header('Accept-Encoding' , 'windows-1251,utf-8;q=0.7,*;q=0.7')
req.add_header('Referer' , 'http://watch.is/login')
opener.open(req)


h = int(sys.argv[1])
#url   = httpSiteUrl + '/top/'

def construct_request(params):
	return '%s?%s' % (sys.argv[0], urllib.urlencode(params))

def showMessage(heading, message, times = 500):
	xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")'%(heading, message, times, icon))


	
	


def GETrr(url):
    
	link = url['url']
    
        cookieJar = cookielib.CookieJar()
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))	    

	req = urllib2.Request('http://watch.is/login', login_data)
	req.add_header('Host' , 'watch.is')
	req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1')
	req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
	req.add_header('Accept-Encoding' , 'gzip, deflate')
	req.add_header('Accept-Language', 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3')
	req.add_header('Accept-Encoding' , 'windows-1251,utf-8;q=0.7,*;q=0.7')
	req.add_header('Referer' , 'http://watch.is/login')
	opener.open(req)

	req = urllib2.Request(link)
	f = opener.open(req)
	a = f.read()
	f.close()
	return a

  

def GET(url):
	try:
		req = urllib2.Request(url)
		req.add_header('Host' , 'watch.is')
		req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1')
		req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
		req.add_header('Accept-Encoding' , 'deflate')
		req.add_header('Accept-Language', 'ru')
		req.add_header('Referer' , 'http://watch.is/')
		f = opener.open(req)
		http = f.read()
		req = urllib2.Request(url)
		f = opener.open(req)
		a = f.read()
		f.close()
		return a
	except:
		showMessage('Не могу открыть URL def GET', url)
		return None



def getCategories(params):

        li = xbmcgui.ListItem('/ - ПОИСК - /')
	uri = construct_request({
		'mode': 'search'
	}) 
	xbmcplugin.addDirectoryItem(h, uri, li, True)
	
	li = xbmcgui.ListItem('Последние')
	uri = construct_request({
		'mode': 'gettop',
		'href': httpSiteUrl + '/'
	})
	xbmcplugin.addDirectoryItem(h, uri, li, True)
	
	li = xbmcgui.ListItem('Жанры')
	uri = construct_request({
		'mode': 'genre'
	})
	
	xbmcplugin.addDirectoryItem(h, uri, li, True)

	li = xbmcgui.ListItem('Лучшие')
	uri = construct_request({
		'mode': 'gettop',
		'href': httpSiteUrl + '/top'
	})
	
	xbmcplugin.addDirectoryItem(h, uri, li, True)
	li = xbmcgui.ListItem('Закладки')
        uri = construct_request({
                'mode': 'gettop',
                'href': httpSiteUrl + '/bookmark'
        })
        xbmcplugin.addDirectoryItem(h, uri, li, True)
	
	xbmcplugin.endOfDirectory(h)
	
def search():
	skbd = xbmc.Keyboard()
	skbd.setHeading('Название фильма или часть названия')
	skbd.doModal()

	SearchString = skbd.getText(0)
	url = httpSiteUrl+'/?search='+ SearchString

	http = GET(url)
	
	if http == None: return False
	r1 = re.compile('<!-- content -->(.*?)<!-- //end content -->',re.S).findall(http)
	r2 = re.compile('<div class="poster">\s*<a href="(.*?)"><img src="(.*?)" width="105"',re.S).findall(r1[0])
	r3 = re.compile('</div>\s*<div class="name"><a href="(.*?)" class="name"><strong>(.*?)</strong> <span>(.*?)</span></a></div>\s*</div>',re.S).findall(r1[0])
	r5 = re.compile('<div class="votes"><img src="/templates/images/vote.png" alt=""><span class="text">(.*?)</span></div>',re.S).findall(r1[0])
	r6 = re.compile('<div class="views"><img src="/templates/images/views.png" alt=""><span class="text">(.*?)</span></div>',re.S).findall(r1[0])
	
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	ii = 0
	for href, img in r2:
			img = httpSiteUrl + img
			alt = r3[ii][1] + ' / ' + r3[ii][2]  + '    -   ' + '[COLOR red]%s[/COLOR]' %r5[ii] + ' / ' + '[COLOR yellow]%s[/COLOR]' %r6[ii]
			ii = ii + 1
			i = xbmcgui.ListItem(alt, iconImage=img, thumbnailImage=img)
#			i.setInfo(type='video', infoLabels={'title': alt, 'plot': text})
			u  = sys.argv[0] + '?mode=PLAY1'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
			i.setProperty('IsPlayable', 'true')
			xbmcplugin.addDirectoryItem(h, u, i)
	try:
		rp = re.compile('<div class="pagination-block">(.*?)</tr></table></div> ', re.DOTALL).findall(http)[0]
		rp2 = re.compile('<td><a href="(.*?)" class="page"><span><span>(.*?)</span></span></a></td>').findall(rp)
		for href, nr in rp2:
			u = sys.argv[0] + '?mode=open'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass
	
	xbmcplugin.endOfDirectory(h)
	
def genre():
	http = GET(httpSiteUrl)
	if http == None: return False
	r1 = re.compile('</a>\s*.<ul>(.*?)</ul>\s*.</li>',re.S).findall(http)
	r2 = re.compile('<li><a href="(.+?)">(.+?)</a></li>',re.S).findall(r1[0])
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	for href, name in r2:
#		i = xbmcgui.ListItem(unicode(name, "cp1251"), iconImage=icon, thumbnailImage=icon)
		i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
		u  = sys.argv[0] + '?mode=open'
		u += '&url=%s'%urllib.quote_plus( httpSiteUrl + href)
		u += '&name=%s'%urllib.quote_plus(name)
		xbmcplugin.addDirectoryItem(h, u, i, True)
	
	xbmcplugin.endOfDirectory(h)


def open(params):
	url = params['url']
	url = urllib.unquote_plus(url)
#	showMessage('url open', url, 3000)
	http = GET(url)
	
	if http == None: return False
	r1 = re.compile('<!-- content -->(.*?)<!-- //end content -->',re.S).findall(http)
#	r2 = re.compile('<div class="poster">(.*?)<div class="preview-block">',re.S).findall(r1[0])
#	r2 = re.compile('<a href="(.*?)"><img src="(.*?)" width=".*" height=".*" alt="" /></a>\s*.*\s*.*\s*.*\s*.*\s*.*\s*.*\s*<div class="name"><a href=".*" class="name"><strong>(.*?)</strong> <span>(.*?)</span></a></div>',re.S).findall(r1[0])
	r2 = re.compile('<div class="poster">\s*<a href="(.*?)"><img src="(.*?)" width="105"',re.S).findall(r1[0])
	r3 = re.compile('</div>\s*<div class="name"><a href="(.*?)" class="name"><strong>(.*?)</strong> <span>(.*?)</span></a></div>\s*</div>',re.S).findall(r1[0])
	r5 = re.compile('<div class="votes"><img src="/templates/images/vote.png" alt=""><span class="text">(.*?)</span></div>',re.S).findall(r1[0])
	r6 = re.compile('<div class="views"><img src="/templates/images/views.png" alt=""><span class="text">(.*?)</span></div>',re.S).findall(r1[0])
#	r3 = re.compile('class="name"><strong>(.*?)</strong>',re.S).findall(r1[0])
	
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	
	name='[COLOR blue]Жанры[/COLOR]'
        li = xbmcgui.ListItem(name)
	url = sys.argv[0] + '?mode=genre'
        xbmcplugin.addDirectoryItem(h, url, li, True)
		
	ii = 0
	for href, img in r2:
			img = httpSiteUrl + img
			#img = icon
			#text = r4[ii]
			#alt = r3[ii][0] + ' / ' + r3[ii][1]
			alt = r3[ii][1] + ' / ' + r3[ii][2] + '    -   ' + '[COLOR red]%s[/COLOR]' %r5[ii] + ' / ' + '[COLOR yellow]%s[/COLOR]' %r6[ii]
			ii = ii + 1
			i = xbmcgui.ListItem(alt, iconImage=img, thumbnailImage=img)
#			i.setInfo(type='video', infoLabels={'title': alt, 'plot': text})
			u  = sys.argv[0] + '?mode=PLAY1'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
			i.setProperty('IsPlayable', 'true')
			xbmcplugin.addDirectoryItem(h, u, i)
	    
	try:
		rp = re.compile('<div class="pagination-block">(.*?)</tr></table></div> ', re.DOTALL).findall(http)[0]
		rp2 = re.compile('<td><a href="(.*?)" class="page"><span><span>(.*?)</span></span></a></td>').findall(rp)
		for href, nr in rp2:
			u = sys.argv[0] + '?mode=open'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
#			rPN = '[B][COLOR yellow]%s[/COLOR][/B]' % rPN
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass
	
	xbmcplugin.endOfDirectory(h)

	
	
def gettop(params):
	url = params['href']
	url = urllib.unquote_plus(url)
#	showMessage('url gettop', url, 3000)
	http = GET(url)
	
	if http == None: return False
	r1 = re.compile('<!-- content -->(.*?)<!-- //end content -->',re.S).findall(http)
#	r2 = re.compile('<div class="poster">(.*?)<div class="preview-block">',re.S).findall(r1[0])
#	r2 = re.compile('<a href="(.*?)"><img src="(.*?)" width=".*" height=".*" alt="" /></a>\s*.*\s*.*\s*.*\s*.*\s*.*\s*.*\s*<div class="name"><a href=".*" class="name"><strong>(.*?)</strong> <span>(.*?)</span></a></div>',re.S).findall(r1[0])
	r2 = re.compile('<div class="poster">\s*<a href="(.*?)"><img src="(.*?)" width="105"',re.S).findall(r1[0])
	r3 = re.compile('</div>\s*<div class="name"><a href="(.*?)" class="name"><strong>(.*?)</strong> <span>(.*?)</span></a></div>\s*</div>',re.S).findall(r1[0])
#	r3 = re.compile('class="name"><strong>(.*?)</strong>',re.S).findall(r1[0])
	r5 = re.compile('<div class="votes"><img src="/templates/images/vote.png" alt=""><span class="text">(.*?)</span></div>',re.S).findall(r1[0])
	r6 = re.compile('<div class="views"><img src="/templates/images/views.png" alt=""><span class="text">(.*?)</span></div>',re.S).findall(r1[0])
	
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	ii = 0
	for href, img in r2:
			img = httpSiteUrl + img
			alt = r3[ii][1] + ' / ' + r3[ii][2]  + '    -   ' + '[COLOR red]%s[/COLOR]' %r5[ii] + ' / ' + '[COLOR yellow]%s[/COLOR]' %r6[ii]
			ii = ii + 1
			i = xbmcgui.ListItem(alt, iconImage=img, thumbnailImage=img)
#			i.setInfo(type='video', infoLabels={'title': alt, 'plot': text})
			u  = sys.argv[0] + '?mode=PLAY1'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
			i.setProperty('IsPlayable', 'true')
			xbmcplugin.addDirectoryItem(h, u, i)
	try:
		rp = re.compile('<div class="pagination-block">(.*?)</tr></table></div> ', re.DOTALL).findall(http)[0]
		rp2 = re.compile('<td><a href="(.*?)" class="page"><span><span>(.*?)</span></span></a></td>').findall(rp)
		for href, nr in rp2:
			u = sys.argv[0] + '?mode=open'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass
	
	xbmcplugin.endOfDirectory(h)
	
def PLAY1(params):
	
	http3 = urllib.unquote_plus(params['url'])
#	showMessage('play url', http3)
	http = GET(urllib.unquote_plus(params['url']))

	if http == None: return False
	r1 = re.compile('<!-- content -->(.*?)function TestEvents',re.S).findall(http)
	rows1 = re.compile('file:"(.+?).mp4').findall(r1[0])

	furl = rows1[0]+'.mp4'
#	showMessage('row1', furl)

    	i = xbmcgui.ListItem(path = furl)
#	xbmc.Player().play(http3, i)

	xbmcplugin.setResolvedUrl(h, True, i)
	


def get_params(paramstring):
	param=[]
	if len(paramstring)>=2:
		params=paramstring
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

params=get_params(sys.argv[2])


mode = None

try:
	mode = urllib.unquote_plus(params['mode'])
except:
	getCategories(params)
	#ROOT()

if mode == 'ROOT':
	ROOT()

if mode == 'OPEN_MOVIES':
	OPEN_MOVIES(params)

if mode == 'OPEN_MOVIES2':
	OPEN_MOVIES2(params)
	
if mode == 'ROOT3':
	ROOT3()

if mode == 'open':  open(params)
if mode == 'PLAY1': PLAY1(params)
	
if mode == 'search': search()

if mode == 'genre': genre()
if mode == 'gettop': gettop(params)
if mode=='AUTH': AUTH()

